package com.zhj.rabbitmq.confirms.waitForConfirmsOrDie;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @program: rabbimmq-demo
 * @description: 批量消息发送确认模式-消息发送
 * @author: zhengjibin
 * @create: 2020-11-18 14:56
 * @Version 1.0
 **/
public class WaitForConfirmsOrDieSendMessage {
    public static void main(String[] args) {
        ConnectionFactory factory = new ConnectionFactory();
        //配置rabbitmq的链接信息
        factory.setHost("122.112.198.94");
        factory.setPort(5672);
        factory.setUsername("admin");
        factory.setPassword("admin");
        Connection connection = null;// 定义rabbitmq的网络连接 ，一个连接
        Channel channel = null;//定义一个链接中的通道
        try {
            connection = factory.newConnection();//通过工厂获得连接
            channel = connection.createChannel();//通过连接获得通道

            String queueName = "orDie_queue";
            String exchangeName = "orDie_exchange";
            String routingkey = "orDieRoutingKey";
            channel.queueDeclare(queueName,true,false,false,null);
            channel.exchangeDeclare(exchangeName,"direct",true);
            channel.queueBind(queueName,exchangeName,routingkey);
            //启动发送者确认模式
            channel.confirmSelect();
            String message = "批量确认发送者确认模式，消息发送测试 第一条消息";
            channel.basicPublish(exchangeName,routingkey,null,message.getBytes("UTF-8"));
            message = "批量确认发送者确认模式，消息发送测试 第二条消息";
            channel.basicPublish(exchangeName,routingkey,null,message.getBytes("UTF-8"));
            //批量确认消息 ,批量确认之前写入通道的数据是否都写入队列中
            //是一个阻塞线程，等待服务器响应，抛出InterruptedException异常则失败需要补发消息，也可以指定超时时间
            //批量确认比普通确认效率更高,因为普通确认需要一个一个去确认
            channel.waitForConfirmsOrDie(1000L);
            System.out.println("消息发送成功");
        } catch (IOException e) {
            System.out.println("消息发送失败");
            e.printStackTrace();
        } catch (TimeoutException e) {
            System.out.println("消息发送失败");
            e.printStackTrace();
        } catch (InterruptedException e) {
            System.out.println("发送者确认失败");
            e.printStackTrace();
        } finally {
            try {
                if (channel != null){
                    channel.close();
                }
                if (connection != null){
                    connection.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        }
    }
}
